package org.ilc.sample.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author malongbo
 */
public class CipherUtil {
    private static MessageDigest md5 = null;

    static {
        try {
            md5 = MessageDigest.getInstance ("MD5");
        } catch (NoSuchAlgorithmException e) {
            //TODO: catch nosuchalgorithmException
            e.printStackTrace ();
        }
    }

    public static String md5(String msg) {
        byte [] bytes = null;

        try {
            bytes = msg.getBytes ("UTF8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace ();
        }
        if (bytes != null && bytes.length > 0) {
            md5.update (bytes);
            StringBuffer buffer = new StringBuffer ();
            for (byte b : md5.digest ()) {
                buffer.append (String.format ("%02x",b&0xff));
            }
            return buffer.toString ();
        }
        return null;
    }
}
